package com.sinochem.yunlian.ship.common.mq;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.common.message.Message;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author: houshihao
 * @description: 发送rocketmq消息 通用服务
 * @date: 2018/3/27 11:08
 * @modified By :
 * @version:
 */
@Component
@Slf4j
public class RocketmqProducerService {

    //使用yml中配置的topic
    public boolean sendImMessage(String msg){
        return this.sendImMessage(msg, producerTopic);
    }

    /**
     * @description:  指定topic发送rocketmq消息
     */
    public boolean sendImMessage(String msg, String topic) {
        log.info("--sendImMessage start-- imMessage info:{}", msg);
        boolean sendSuccess = false;
        Message message = new Message(topic, msg.getBytes());
        try {
            SendResult sendResult = defaultProducer.send(message);
            sendSuccess = sendResult != null && sendResult.getSendStatus() != null && sendResult.getSendStatus() == SendStatus.SEND_OK;
            if (sendSuccess) {
                log.info("--sendImMessage success-- msgId:{} ,imMessage info:{}", sendResult.getMsgId(),msg);
            }
        } catch (Exception e) {
            log.error("--ImMessageService#sendImMessage error-- imMessage info:{}", msg, e);
        }
        return sendSuccess;
    }

//
    @Value("${rocketmq.producer.topic:#{null}}")
    private String producerTopic;

    @Resource
    private DefaultMQProducer defaultProducer;
}
